package com.xunyin.modules.mtstore.rest;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.util.StrUtil;
import com.xunyin.common.CommonResult;
import com.xunyin.constant.ShopConstants;
import com.xunyin.dozer.service.IGenerator;
import com.xunyin.enums.StatusEnum;
import com.xunyin.exception.BadRequestException;
import com.xunyin.modules.aop.ForbidSubmit;
import com.xunyin.modules.log.Log;
import com.xunyin.modules.mp.config.WxMaConfiguration;
import com.xunyin.modules.mp.config.WxMpConfiguration;
import com.xunyin.modules.mtstore.domain.MtStoreRoom;
import com.xunyin.modules.mtstore.service.MtStoreRoomService;
import com.xunyin.modules.qrcode.domain.QrcodeDO;
import com.xunyin.modules.qrcode.service.QrcodeService;
import com.xunyin.modules.qrcode.vo.DeskQrcodeRespVO;
import com.xunyin.modules.qrcode.vo.QrcodeVO;
import com.xunyin.modules.security.security.TokenUtil;
import com.xunyin.modules.security.security.vo.JwtUser;
import com.xunyin.modules.storeroom.param.TStoreRoomQueryParam;
import com.xunyin.modules.storeroom.service.dto.TStoreRoomQueryCriteria;
import com.xunyin.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

import static com.xunyin.common.CommonResult.success;

/**
 * 包间管理类controller
 * <p>
 * Created by xunyin
 * CopyRight 讯音云商 https://www.tonetn.com
 */
@Slf4j
@Api(tags = "共享空间:包间管理2.0")
@RestController
@RequestMapping("api")
public class MtStoreRoomController {

    private final IGenerator generator;

    private final MtStoreRoomService mtStoreRoomService;

    private final QrcodeService qrcodeService;

    private final RedisUtils redisUtils;

    private final TokenUtil tokenUtil;

    public MtStoreRoomController(MtStoreRoomService mtStoreRoomService, IGenerator generator, QrcodeService qrcodeService, RedisUtils redisUtils, TokenUtil tokenUtil) {
        this.mtStoreRoomService = mtStoreRoomService;
        this.generator = generator;
        this.qrcodeService = qrcodeService;
        this.redisUtils = redisUtils;
        this.tokenUtil = tokenUtil;
    }

    @Log("查询房间")
    @ApiOperation(value = "查询房间")
    @GetMapping(value = "/mtStoreRoom")
    //@PreAuthorize("hasAnyRole('admin','MAINPART_ALL','MAINPART_SELECT')")
    public ResponseEntity getMtStoreRoom(HttpServletRequest request, TStoreRoomQueryCriteria criteria, Pageable pageable) {
//        if (criteria.getStoreId() == 0) {
//            criteria.setStoreId(null);
//        }
        criteria.setStoreId(null);
        JwtUser user = tokenUtil.getJwtUser(tokenUtil.getToken(request));
        if (!user.getRoleIdList().contains(Long.valueOf(1L))) {
            criteria.setStoreId(user.getStoreIdList());
        }
        Map<String, Object> queryAll = mtStoreRoomService.queryAll(criteria, pageable);
        return new ResponseEntity<>(queryAll, HttpStatus.OK);
    }

    @ForbidSubmit
    @Log("新增房间")
    @ApiOperation(value = "新增房间")
    @PostMapping(value = "/mtStoreRoom")
    @PreAuthorize("hasAnyRole('admin','YXSYSTEMUSERLEVEL_ALL','YXSYSTEMUSERLEVEL_CREATE')")
    public ResponseEntity create(@Validated @RequestBody MtStoreRoom resources) {
        resources.setStatus(1);
/*        BigDecimal bigDecimal = new BigDecimal(100);
        BigDecimal price = bigDecimal.multiply(resources.getPrice());
        resources.setPrice(price);*/
        return new ResponseEntity<>(mtStoreRoomService.save(resources), HttpStatus.CREATED);
    }

    @ForbidSubmit
    @Log("修改房间")
    @ApiOperation(value = "修改房间")
    @PutMapping(value = "/mtStoreRoom")
    @PreAuthorize("hasAnyRole('admin','YXSYSTEMUSERLEVEL_ALL','YXSYSTEMUSERLEVEL_EDIT')")
    public ResponseEntity update(@Validated @RequestBody MtStoreRoom resources) {
/*        BigDecimal bigDecimal = new BigDecimal(100);
        BigDecimal price = bigDecimal.multiply(resources.getPrice());
        resources.setPrice(price);*/
        mtStoreRoomService.saveOrUpdate(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @ForbidSubmit
    @Log("删除")
    @ApiOperation(value = "删除")
    @DeleteMapping(value = "/mtStoreRoom/{id}")
    @PreAuthorize("hasAnyRole('admin','YXSYSTEMUSERLEVEL_ALL','YXSYSTEMUSERLEVEL_DELETE')")
    public ResponseEntity delete(@PathVariable Integer id) {
        mtStoreRoomService.removeById(id);
        return new ResponseEntity(HttpStatus.OK);
    }

    @Log("根据门店id获取房间列表")
    @ApiOperation("根据门店id获取房间列表")
    @PostMapping(value = "/listRoom")
    // @PreAuthorize("@el.check('yxSystemStore:list')")
    public ResponseEntity<Object> listRoom(@Validated @RequestBody TStoreRoomQueryParam queryParam) {

        return new ResponseEntity<>(mtStoreRoomService.listRoom(queryParam), HttpStatus.OK);

    }

    /**
     * 更新房间上线状态，A：有效/启用；D：无效
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateRoomOnlineStatus")
    @CrossOrigin
    public ResponseEntity updateRoomOnlineStatus(HttpServletRequest request, @RequestBody Map<String, Object> params) {
        // String token = request.getHeader("Access-Token");

        String roomOnlineStatus = params.get("roomOnlineStatus") != null ? params.get("roomOnlineStatus").toString() : StatusEnum.ENABLED.getKey();
        Integer roomId = params.get("roomId") == null ? 0 : Integer.parseInt(params.get("roomId").toString());
        mtStoreRoomService.updateRoomOnlineStatus(roomId, roomOnlineStatus);
        return new ResponseEntity(HttpStatus.OK);

        //return getSuccessResult(true);
    }


    @PostMapping(value = "/single-qrcode")
    @Operation(summary = "生成单个二维码")
    public CommonResult<DeskQrcodeRespVO> getSingleQrcode(HttpServletRequest httpServletRequest, @RequestBody QrcodeVO qrcodeVO) {

        log.info("qrcodeVO.getStoreId():"+qrcodeVO.getStoreId());
        log.info("qrcodeVO.getStoreRoomId():"+qrcodeVO.getStoreRoomId());

        WxMaService wxMaService = WxMaConfiguration.getWxMaService();

/*        String scene = "storeId=" + qrcodeVO.getStoreId()
                + "&storeName=" + qrcodeVO.getStoreName()
                + "&storeRoomId=" +  qrcodeVO.getStoreRoomId()
                + "&storeRoomName=" +  qrcodeVO.getStoreRoomName()
                + "&roomType=" +  qrcodeVO.getRoomType()
                + "&deposMoney=" +  qrcodeVO.getDeposMoney()
                + "&reMoney=" +  qrcodeVO.getReMoney()
                + "&minCharge=" +  qrcodeVO.getMinCharge();*/
        String scene = "storeId=" + qrcodeVO.getStoreId() + "&storeRoomId=" +  qrcodeVO.getStoreRoomId();

        QrcodeDO qrcodeDO = qrcodeService.createMiniQrcode(ShopConstants.PAGE_GOOD_HOME,scene,false,qrcodeVO.getEnv(),wxMaService);
        QrcodeDO qrcodeDO1 = qrcodeService.createQrcode(ShopConstants.PAGE_GOOD_HOME,scene,false);

        //String miniQrcode = ServletUtils.getRequstHost(httpServletRequest) + "/admin-api/"+qrcodeDO.getSrc();
        String adminApiUrl = redisUtils.getY(ShopConstants.ADMIN_API_URL);
        if (StrUtil.isBlank(adminApiUrl)) {
            throw new BadRequestException("请配置后台-->商城配置-->商城系统配置-->后台Api地址");
        }
        final WxMpService wxService = WxMpConfiguration.getWxMpService();
        if (wxService == null) {
            throw new IllegalArgumentException("未找到对应配置的服务，请核实！");
        }
        //String miniQrcode = ServletUtils.getRequstHost(httpServletRequest) + "/"+qrcodeDO.getSrc();
        String miniQrcode = adminApiUrl + "/"+qrcodeDO.getSrc();
        log.info("miniQrcode:"+miniQrcode);
        //String normalQrcode = ServletUtils.getRequstHost(httpServletRequest) + "/admin-api/"+qrcodeDO1.getSrc();

        DeskQrcodeRespVO deskQrcodeRespVO = DeskQrcodeRespVO.builder()
                .miniQrcode(miniQrcode).build();
        return success(deskQrcodeRespVO);

    }
}
